<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <input type="text" onkeyup="test(this)">

    <script>
        function test(obj){
            let str = obj.value.replace(/\s/g,"");
            let temp = "";
            for(let i=0;i<str.length;i++){
                temp+=str.substring(i,i+1);
                if(i!=0 && i!=str.length-1 && (i+1)%4==0){
                   temp+=" ";
                }
            }
            obj.value = temp;
        }
    </script>
</body>
</html>